package com.snow.common.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.snow.common.component.SystemAnnexComponent;
import com.snow.exception.CommonRuntimeException;
import com.snow.view.WebResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/system-annex")
public class SystemAnnexController {

    private final StringRedisTemplate stringRedisTemplate;
    private final SystemAnnexComponent systemAnnexComponent;

    @Getter
    @Setter
    public static class WechatApplyUploadAnnexParams {
        private MultipartFile file;
    }

    @PostMapping("/upload-annex")
    public WebResponse<String> uploadAnnex(WechatApplyUploadAnnexParams wechatApplyUploadAnnexParams) {
        try {
            String cashId = IdUtil.fastSimpleUUID();
            stringRedisTemplate.opsForValue().set(cashId, wechatApplyUploadAnnexParams.getFile().getOriginalFilename() + ":" + Base64.encode(wechatApplyUploadAnnexParams.getFile().getInputStream()), 2, TimeUnit.HOURS);
            return WebResponse.success(cashId);
        } catch (IOException e) {
            throw new CommonRuntimeException("上传文件流读取失败");
        }
    }

    @GetMapping("/preview-annex")
    public String previewAnnex(String path) {
        return systemAnnexComponent.getPreviewUrl(path);
    }

    @GetMapping("/preview-annex-base")
    public String previewAnnexBase(String objName) {
        return Base64.encode(systemAnnexComponent.getPreviewUrl(objName));
    }
}
